import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

let router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'index',
      component: ()=>import('@/pages/index')
    },
    {
      path: '/insert',
      name: 'insert',
      component: ()=>import('@/pages/insert')
    },
    {
      path: '/details',
      name: 'details',
      component: ()=>import('@/pages/details')
    },
    {
      path: '/login',
      name: 'login',
      component: ()=>import('@/pages/login/login.vue')
    },
  ]
})

// 导航守卫
router.beforeEach((to, from, next) => {
  // 导航守卫，
  let token = localStorage.getItem("token") || "";
  if (token) { // 已登录
    next();
  } else {
    // 只有在非授权回调路径时才重定向到微信授权页面
    if (to.path !== '/') {
      const appID = "wx0321989f72146a62"; // 替换为你的微信应用 ID
      const redirect_uri = encodeURIComponent('http://192.168.0.31:8080/'); // 注意这里的路径
      const state = 'STATE'; // 用于安全验证，可以是任意字符串
      const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appID}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect`;
      window.location.href = url;
    } else {
      next(); // 允许进入授权回调页面
    }
  }
})
export default router;
